package com.mazaiting.jetpack.architecture.work

import android.arch.lifecycle.Observer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.work.*
import com.mazaiting.jetpack.R
import java.util.*
import java.util.concurrent.TimeUnit

class WorkManagerActivity : AppCompatActivity() {
  
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_work_manager)

//    oneWork()
    moreWork()
  }
  
  private fun moreWork() {
    // 创建任务
    val workerRequest: WorkRequest = PeriodicWorkRequest.Builder(CompressWorker::class.java, 15, TimeUnit.MINUTES).build()
    // 执行任务
    WorkManager.getInstance().enqueue(workerRequest)
  }
  
  /**
   * 任务执行一次
   */
  private fun oneWork() {
    // 任务约束
    val constraint: Constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .build()
    // 创建执行一次的工作请求
    val compressWork: WorkRequest = OneTimeWorkRequest.Builder(CompressWorker::class.java)
            .setConstraints(constraint)
            .build()
    // 根据ID来观察任务执行
    WorkManager.getInstance().getStatusById(compressWork.id)
            .observe(this, Observer { workStatus ->
              if (null != workStatus && workStatus.state.isFinished) {
                Toast.makeText(this, "执行完成", Toast.LENGTH_SHORT).show()
              }
            })
    // 执行工作请求
    WorkManager.getInstance().enqueue(compressWork)
    // 取消任务
//    WorkManager.getInstance().cancelWorkById(compressWork.id)
  }
}
